package io.renren.modules.app.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.app.dao.ImApplyDao;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.ImApplyService;
import io.renren.modules.app.service.ImFriendService;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.tio.TioServerConfig;
import io.renren.modules.app.tio.WsOnlineContext;
import io.renren.modules.app.utils.ChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.Uuid;
import org.tio.websocket.common.WsResponse;


@Service("imApplyService")
public class ImApplyServiceImpl extends ServiceImpl<ImApplyDao, ImApplyEntity> implements ImApplyService {

    @Autowired
    ImFriendService imFriendService;
    @Autowired
    UserService userService;
    @Autowired
    ImApplyDao imApplyDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params,UserEntity user) {
        /*IPage<ImApplyEntity> page = this.page(
                new Query<ImApplyEntity>().getPage(params),
                new QueryWrapper<ImApplyEntity>().eq("friend_id", user.getUserId())
        );*/
        IPage<ImApplyEntity> page = imApplyDao.selectPageAll(new Query<ImApplyEntity>().getPage(params),user);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public Map<String,Object> handle(ImApplyEntity imApply, UserEntity user) throws JsonProcessingException {
        ImApplyEntity ia = new ImApplyEntity();
        ia.setId(imApply.getId());
        ia.setStatus(imApply.getStatus());
        // 设置该申请状态
        this.updateById(ia);
        //查询实体，申请表的数据
        ia = this.getById(ia.getId());
        UserEntity u = userService.getById(ia.getUserId());
        // 加入到对方好友列表
        ImFriendEntity friend = new ImFriendEntity();
        friend.setFriendId(user.getUserId().intValue());
        friend.setUserId(ia.getUserId());
        friend.setNickname(ia.getNickname());
        friend.setLookme(ia.getLookme());
        friend.setLookhim(ia.getLookhim());
        imFriendService.save(friend);
        // 将对方加入到我的好友列表
        ImFriendEntity friend2 = new ImFriendEntity();
        friend2.setFriendId(ia.getUserId());
        friend2.setUserId(user.getUserId().intValue());
        friend2.setNickname(imApply.getNickname());
        friend2.setLookme(imApply.getLookme());
        friend2.setLookhim(imApply.getLookhim());
        imFriendService.save(friend2);
        Map<String, Object> map = new HashMap<>();
        // 消息推送
        if (imApply.getStatus().equals("agree")) {
            //推送给申请人
            Message message = new Message();
            message.setId(String.valueOf((new Date()).getTime()));
            message.setFrom_avatar(user.getAvatar());
            message.setFrom_name(!ia.getNickname().equals("")?ia.getNickname():(!user.getNickname().equals("")?user.getNickname():user.getUsername()));
            message.setFrom_id(user.getUserId().toString());
            message.setTo_id(ia.getUserId().toString());
            message.setTo_name(!imApply.getNickname().equals("")?imApply.getNickname():(!u.getNickname().equals("")?u.getNickname():u.getUsername()));
            message.setTo_avatar(u.getAvatar());
            message.setChat_type("user");
            message.setType("system");
            message.setData("你们已经是好友，可以开始聊天啦");
            message.setCreate_time((new Date()).getTime());
            message.setIsremove(0);
            //发送信息
            SendInfo sendInfo = new SendInfo();
            sendInfo.setCode(ChatUtils.MSG_MESSAGE);
            sendInfo.setMessage(message);
            WsResponse wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo), TioServerConfig.CHARSET);
            ChannelContext cco = WsOnlineContext.getChannelContextByUser(user.getUserId().toString());
            Tio.sendToUser(cco.groupContext, ia.getUserId().toString(), wsResponse);

            map.put("message",message);
            Message message1 = new Message();
            message1.setId(String.valueOf((new Date()).getTime()));
            message1.setFrom_avatar(u.getAvatar());
            message1.setFrom_name(!imApply.getNickname().equals("")?imApply.getNickname():(!u.getNickname().equals("")?u.getNickname():u.getUsername()));
            message1.setFrom_id(ia.getUserId().toString());
            message1.setTo_id(user.getUserId().toString());
            message1.setTo_name(!ia.getNickname().equals("")?ia.getNickname():(!user.getNickname().equals("")?user.getNickname():user.getUsername()));
            message1.setTo_avatar(user.getAvatar());
            message1.setChat_type("user");
            message1.setType("system");
            message1.setData("你们已经是好友，可以开始聊天啦");
            message1.setCreate_time((new Date()).getTime());
            message1.setIsremove(0);
            map.put("mess",message1);
        }
        return map;
    }

}
